import re

from rest_framework import serializers

from .models import SystemUser


class SystemUserSerializer(serializers.ModelSerializer):

    status = serializers.BooleanField(read_only=True)
    role_name = serializers.CharField(label='用户角色', source='role.name', read_only=True)

    class Meta:
        model = SystemUser
        fields = ['id', 'username', 'nick_name', 'mobile', 'password', 'email', 'role', 'role_name', 'status']
        extra_kwargs = {
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '请输入8-20个字符的密码',
                    'max_length': '请输入8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        if not re.match(r'^1[356789]\d{9}$', value):
            raise serializers.ValidationError('输入的手机号格式不正确')
        return value

    # def validate_email(self, value):
    #     # print(value)
    #     if not re.match(r'^[0-9a-zA-Z_.-]+@[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*\\.[0-9a-zA-Z-]{2,6}$', value):
    #         raise serializers.ValidationError('输入的邮箱格式不正确')
    #     return value

    def create(self, validated_data):
        password = validated_data.pop('password')
        user = SystemUser(**validated_data)
        user.set_password(password)
        user.save()
        return user
